package com.sugon.modules.kpi.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import com.sugon.modules.analyse.consts.KpiTarget;
import com.sugon.modules.analyse.model.chart.KpiTargetBarEchartOptionDataVO;
import com.sugon.modules.analyse.model.vo.DeviceKpiStatParamVO;
import com.sugon.modules.kpi.model.StopLineStatVO;
import com.sugon.modules.kpi.service.IKpiTargetComputor;
import com.sugon.modules.report.service.IStopLineOrDeviceManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.math.RoundingMode;
import java.util.Map;

/**
 * @author ： YuXD
 * @description： MTTR KPI计算器实现类
 * @date ： 2020-11-15 下午 3:27
 * @version: 1.0
 */
@Service
public class MTTRKPIComputorImpl implements IKpiTargetComputor {

    @Autowired
    private IStopLineOrDeviceManager stopLineOrDeviceManager;

    @Override
    public KpiTargetBarEchartOptionDataVO compute(DeviceKpiStatParamVO kpiStatParam) {
        KpiTargetBarEchartOptionDataVO kpiTargetBarEchartOption = new KpiTargetBarEchartOptionDataVO("",null);
        // 根据不同的设备组织级别统计出不同的MTTR原始数据
        KpiTarget kpiTarget = getType();
        Assert.isTrue(kpiStatParam.getLevel() >= kpiTarget.getLevel(), "不支持当前设备组织[" + kpiTarget.getLabel() + "]维度的KPI计算！");
        // 获取不同设备组织下的MTTR原始统计数据
        Map<Integer, StopLineStatVO> mttrStatMap = stopLineOrDeviceManager.doYearlyStopLineOrDeviceHourTotalStat(kpiStatParam);
        // 当前月份
        Integer currentMonth = com.sugon.modules.utils.DateUtil.month(null);
        // 待统计的年份
        Integer statYearly = kpiStatParam.getYearly();
        // 今年年份
        int thisYear = DateUtil.thisYear();
        for (int i = 1; i <= 12; i++) {
            // 年份没到或者月份没到的一律默认为0
            if ((statYearly > thisYear) || (statYearly == thisYear && i > currentMonth)) {
                kpiTargetBarEchartOption.add(0.0);
            } else {
                StopLineStatVO stopLineStat = mttrStatMap.get(i);
                // 如果本月没有停线统计，那么默认生成次数1，时长为0的记录
                if(stopLineStat == null){
                    stopLineStat = new StopLineStatVO(i,1.0,0.0);
                }
                kpiTargetBarEchartOption.add(NumberUtil.div(stopLineStat.getMinuteTotal(), stopLineStat.getTimes(), 2, RoundingMode.HALF_UP));
            }
        }
        return kpiTargetBarEchartOption;
    }

    @Override
    public KpiTarget getType() {
        return KpiTarget.MTTR;
    }

}
